using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace FShaderInspector
{
    /// <summary>
    /// 编辑器状态缓存
    /// </summary>
    public class EditorCache
    {
        /// <summary> 抽屉数据 </summary>
        [System.Serializable]
        public class DrawerData
        {
            public List<string> keys = new();
            public List<bool> values = new();

            public DrawerData(Dictionary<string, bool> dir)
            {
                foreach (var item in dir)
                {
                    keys.Add(item.Key);
                    values.Add(item.Value);
                }
            }

            public Dictionary<string, bool> ToDictionary()
            {
                var dir = new Dictionary<string, bool>();
                for (var i = 0; i < keys.Count; i++)
                    dir.Add(keys[i], values[i]);

                return dir;
            }
        }

        /// <summary> 单例 </summary>
        public static EditorCache instance
        {
            get
            {
                if (_instance == null)
                {
                    // 初始化时读取一次 Json，读取成功后清空记录信息
                    _instance = new EditorCache();
                    if (File.Exists(_cachePath))
                    {
                        var drawerData = JsonUtility.FromJson<DrawerData>(File.ReadAllText(_cachePath));
                        if (drawerData != null)
                        {
                            _instance._drawersDataDir = drawerData.ToDictionary();
                            File.WriteAllText(_cachePath, string.Empty);
                        }
                    }

                    EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
                }

                return _instance;
            }
        }
        static EditorCache _instance;

        /// <summary> 缓存存储路径 </summary>
        const string _cachePath = "Library/FShaderGUITempRecord.json";

        /// <summary> 折页数据字典 </summary>
        Dictionary<string, bool> _drawersDataDir = new();

        /// <summary>
        /// 获取 key 字符串
        /// </summary>
        /// <param name="target"></param>
        /// <param name="propName"></param>
        public string GetPropertyKey(Object target, string propName)
        {

            var guid = AssetDatabase.GUIDFromAssetPath(AssetDatabase.GetAssetPath(target));
            var keyStr = $"{propName}_{guid}";
            _drawersDataDir.TryAdd(keyStr, false);

            return keyStr;
        }

        /// <summary>
        /// 获取 key 值
        /// </summary>
        /// <param name="key">key字符串</param>
        public bool GetKey(string key)
        {
            if (_drawersDataDir.TryGetValue(key, value: out var value))
                return value;

            _drawersDataDir.Add(key, false);
            return false;
        }

        /// <summary>
        /// 设置 key 值
        /// </summary>
        /// <param name="key">key字符串</param>
        /// <param name="value">bool值</param>
        public void SetKey(string key, bool value) => _drawersDataDir[key] = value;

        /// <summary>
        /// 编辑器变化时调用
        /// </summary>
        /// <param name="state">状态</param>
        static void OnPlayModeStateChanged(PlayModeStateChange state)
        {
            if (state != PlayModeStateChange.ExitingEditMode)
                return;

            // 退出编辑器模式时，进行一次保存
            var jsonStr = JsonUtility.ToJson(new DrawerData(instance._drawersDataDir), true);
            File.WriteAllText(_cachePath, jsonStr);
            EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
        }
    }
}